import React, { useState, useEffect } from 'react';
import { UploadOutlined, FileOutlined, ReloadOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import type { UploadProps, UploadFile } from 'antd';
import { Button, Upload, message, List, Card, Tag, Space, Spin, Alert, Empty, Grid } from 'antd';

const { useBreakpoint } = Grid;

interface FileItem {
  fileName: string;
  fileSize?: string;
  uploadTime?: string;
  uploadName?: string;
}

// 响应式容器组件
const ResponsiveContainer: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const screens = useBreakpoint();

  return (
    <div style={{
      padding: screens.xs ? '12px' : screens.md ? '16px' : '24px',
      maxWidth: '1000px',
      margin: '0 auto',
      width: '100%',
      boxSizing: 'border-box'
    }}>
      {children}
    </div>
  );
};

// 响应式卡片组件
const ResponsiveCard: React.FC<{
  title: string | React.ReactNode;
  children: React.ReactNode;
  extra?: React.ReactNode;
  style?: React.CSSProperties;
}> = ({ title, children, extra, style = {} }) => {
  const screens = useBreakpoint();

  return (
    <Card
      title={title}
      extra={extra}
      style={{
        marginBottom: screens.xs ? '16px' : '24px',
        ...style
      }}
      bodyStyle={{
        padding: screens.xs ? '12px' : '16px'
      }}
    >
      {children}
    </Card>
  );
};

// 响应式按钮组件
const ResponsiveButton: React.FC<{
  children: React.ReactNode;
  type?: 'primary' | 'default' | 'dashed' | 'link' | 'text';
  icon?: React.ReactNode;
  onClick?: () => void;
  loading?: boolean;
  disabled?: boolean;
  size?: 'small' | 'middle' | 'large';
}> = ({ children, type = 'default', icon, onClick, loading = false, disabled = false, size }) => {
  const screens = useBreakpoint();

  return (
    <Button
      type={type}
      icon={icon}
      onClick={onClick}
      loading={loading}
      disabled={disabled}
      size={size || (screens.xs ? 'small' : 'middle')}
      block={screens.xs}
    >
      {children}
    </Button>
  );
};

const App: React.FC = () => {
  const [uploadedFiles, setUploadedFiles] = useState<FileItem[]>([]);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const screens = useBreakpoint();

  // 组件加载时获取已上传的文件列表
  useEffect(() => {
    fetchUploadedFiles();
  }, []);

  // 获取已上传文件列表 - 使用 POST 请求
  const fetchUploadedFiles = async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch('/api/user/queryfile', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include', // 包含会话凭证
      });

      const result = await response.json();

      if (result.status === 'success' && Array.isArray(result.fileList)) {
        setUploadedFiles(result.fileList);
      } else {
        const errorMsg = result.message || '获取文件列表失败';
        setError(errorMsg);
        message.error(errorMsg);
      }
    } catch (error) {
      console.error('获取文件列表错误:', error);
      const errorMsg = '网络错误，无法获取文件列表';
      setError(errorMsg);
      message.error(errorMsg);
    } finally {
      setLoading(false);
    }
  };

  const handleChange: UploadProps['onChange'] = ({ file, fileList: newFileList }) => {
    setFileList(newFileList);

    // 当文件状态改变时
    if (file.status === 'done') {
      // 获取后端返回的数据
      const response = file.response;
      console.log('后端返回数据:', response);

      // 从后端响应中获取具体参数
      if (response) {
        const { status, message: msg } = response;

        if (status === 'success') {
          message.success(msg || '文件上传成功！');
          // 上传成功后重新获取文件列表
          fetchUploadedFiles();
          // 清空上传文件列表
          setFileList([]);
        } else {
          const errorMsg = msg || '上传失败';
          message.error(errorMsg);
        }
      }
    } else if (file.status === 'error') {
      // 处理上传错误
      const errorMessage = file.response?.message || '上传失败';
      message.error(`${file.name} 上传失败: ${errorMessage}`);
    }
  };

  const uploadProps: UploadProps = {
    action: '/api/user/upload',
    fileList, // 控制上传列表
    onChange: handleChange,
    // 禁用多文件上传
    multiple: false,
    // 显示上传进度
    showUploadList: {
      showRemoveIcon: true,
      showDownloadIcon: false,
      showPreviewIcon: false,
    },
    onRemove: (file) => {
      console.log('删除文件:', file);
      return true; // 允许删除
    },
    beforeUpload: (file) => {
      // 文件上传前的验证
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        message.error('文件大小不能超过10MB');
        return false;
      }
      return true;
    },
    headers: {
      // 如果需要传递认证信息，可以在这里添加
    },
    withCredentials: true, // 包含会话凭证
  };

  // 格式化时间
  const formatTime = (timeStr?: string) => {
    if (!timeStr) return '未知时间';
    try {
      return new Date(timeStr).toLocaleString();
    } catch (e) {
      return timeStr;
    }
  };

  return (
    <ResponsiveContainer>
      <ResponsiveCard
        title="文件上传"
        extra={
          <Space>
            <ResponsiveButton
              icon={<ReloadOutlined />}
              onClick={fetchUploadedFiles}
              loading={loading}
            >
              {screens.xs ? '刷新' : '刷新列表'}
            </ResponsiveButton>
          </Space>
        }
      >
        <Upload {...uploadProps}>
          <ResponsiveButton icon={<UploadOutlined />}>
            {screens.xs ? '上传文件' : '点击上传文件'}
          </ResponsiveButton>
        </Upload>
        <div style={{
          marginTop: '16px',
          fontSize: screens.xs ? '11px' : '12px',
          color: '#999'
        }}>
          支持单个文件上传，文件大小不超过10MB
        </div>
      </ResponsiveCard>

      <ResponsiveCard
        title={
          <Space>
            <span>已上传文件</span>
            <Tag color="blue">{uploadedFiles.length}</Tag>
          </Space>
        }
        extra={
          <ResponsiveButton
            type="primary"
            onClick={fetchUploadedFiles}
            loading={loading}
            disabled={loading}
            icon={<ReloadOutlined />}
          >
            {screens.xs ? '' : '刷新'}
          </ResponsiveButton>
        }
      >
        {error && (
          <Alert
            message="加载失败"
            description={error}
            type="error"
            showIcon
            icon={<ExclamationCircleOutlined />}
            style={{ marginBottom: 16 }}
            action={
              <Button size="small" onClick={fetchUploadedFiles}>
                重试
              </Button>
            }
          />
        )}

        {loading ? (
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            <Spin size="large" />
            <div style={{ marginTop: 16, color: '#999' }}>加载文件列表中...</div>
          </div>
        ) : uploadedFiles.length > 0 ? (
          <List
            dataSource={uploadedFiles}
            renderItem={file => (
              <List.Item>
                <List.Item.Meta
                  avatar={<FileOutlined style={{
                    fontSize: screens.xs ? '20px' : '24px',
                    color: '#1890ff'
                  }} />}
                  title={
                    <Space direction={screens.xs ? 'vertical' : 'horizontal'} align={screens.xs ? 'start' : 'center'}>
                      <span style={{
                        fontWeight: 'bold',
                        fontSize: screens.xs ? '14px' : '16px',
                        wordBreak: 'break-word'
                      }}>
                        {file.fileName}
                      </span>
                      <Tag color="green" style={{ marginTop: screens.xs ? '4px' : 0 }}>
                        上传成功
                      </Tag>
                    </Space>
                  }
                  description={
                    <Space direction="vertical" size={0} style={{ width: '100%' }}>
                      {file.fileSize && (
                        <div style={{ fontSize: screens.xs ? '12px' : '14px' }}>
                          <span style={{ color: '#666' }}>文件大小: </span>
                          {file.fileSize}
                        </div>
                      )}
                      {file.uploadTime && (
                        <div style={{ fontSize: screens.xs ? '12px' : '14px' }}>
                          <span style={{ color: '#666' }}>上传时间: </span>
                          {formatTime(file.uploadTime)}
                        </div>
                      )}
                      {file.uploadName && (
                        <div style={{ fontSize: screens.xs ? '12px' : '14px' }}>
                          <span style={{ color: '#666' }}>上传用户: </span>
                          {file.uploadName}
                        </div>
                      )}
                    </Space>
                  }
                />
              </List.Item>
            )}
            pagination={{
              pageSize: screens.xs ? 5 : 10,
              showSizeChanger: !screens.xs,
              showQuickJumper: !screens.xs,
              showTotal: !screens.xs ? (total, range) =>
                `第 ${range[0]}-${range[1]} 条，共 ${total} 条` : undefined,
              simple: screens.xs,
              size: screens.xs ? 'small' : 'default'
            }}
          />
        ) : (
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={
              error ? "加载文件列表失败，请重试" : "暂无已上传文件"
            }
          >
          </Empty>
        )}
      </ResponsiveCard>
    </ResponsiveContainer>
  );
};

export default App;
